// 2025/11/11
// K个一组反转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* list)
    {
        ListNode head;
        while(list)
        {
            ListNode* next = list->next;
            list->next = head.next;
            head.next = list;
            list = next;
        }
        return head.next;
    }

    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode phead(0, head);
        ListNode *prev = &phead, *cur = prev, *next = nullptr;
        while(cur)
        {
            int i = 0;
            for(i = 0; i < k && cur; i++)
            {
                cur = cur->next;
            }
            if(i == k && cur)
            {
                ListNode* tail = prev->next;
                next = cur->next;
                cur->next = nullptr;
                prev->next = reverseList(prev->next);
                tail->next = next;
                prev = tail;
                cur = prev;
            }
        }
        return phead.next;
    }
};